package org.amphiprion.descentv2assistant.dao.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.amphiprion.descentv2assistant.App;
import org.amphiprion.descentv2assistant.ApplicationConstants;
import org.amphiprion.descentv2assistant.entity.Product;
import org.amphiprion.descentv2assistant.util.PreferenceUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;

public class ProductXmlDao extends AbstractXmlDao {
	private static ProductXmlDao instance;

	public static ProductXmlDao getInstance() {
		if (instance == null) {
			instance = new ProductXmlDao();
		}
		return instance;
	}

	public List<Product> getProducts() {
		if (App.products != null) {
			return App.products;
		}

		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(PreferenceUtil.context);

		List<Product> result = new ArrayList<Product>();
		String lng = PreferenceUtil.getLanguage();
		InputStream is = null;
		try {
			File f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/products.xml");

			if (f.exists()) {
				is = new FileInputStream(f);
			}
			if (is == null) {
				is = App.class.getResourceAsStream("/products.xml");
			}

			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			builderFactory.setNamespaceAware(true);

			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(is);

			NodeList list = document.getElementsByTagName("product");
			for (int i = 0; i < list.getLength(); i++) {
				Element productNode = (Element) list.item(i);
				String id = productNode.getAttributes().getNamedItem("id").getNodeValue();

				// NAME
				Element localizedNode = (Element) productNode.getElementsByTagName("name").item(0);
				String name = getLocalizedText(localizedNode, lng);

				Product product = new Product(id);
				product.setName(name);

				product.setOwned(pref.getBoolean("PRODUCT_OWNED_" + id, true));
				result.add(product);
			}
			is.close();
			App.products = result;
			return result;
		} catch (Throwable e) {
			Log.e(ApplicationConstants.PACKAGE, "", e);
			if (is != null) {
				try {
					is.close();
				} catch (Throwable ex) {
				}
			}
			return null;
		}
	}

	public Product getProduct(String id) {
		List<Product> abs = getProducts();
		if (abs != null) {
			for (Product ab : abs) {
				if (ab.getId().equals(id)) {
					return ab;
				}
			}
		}
		Product ab = new Product(id);
		ab.setName(id + ": NOT FOUND");
		return ab;
	}
}
